package com.phoneinfo.mapper.impl;

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.phoneinfo.bean.Info;
import com.phoneinfo.bean.Page;
import com.phoneinfo.mapper.InfoMapper;

public class InfoMapperImpl implements InfoMapper {

	@Override
	public int searchAllCount() {
		String path="phoneinfo.xml";
		int result=0;
		Reader reader=null;
		SqlSession session=null;
		try {
			reader=Resources.getResourceAsReader(path);
			SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
			SqlSessionFactory factory = builder.build(reader);
			session = factory.openSession();
			result = session.selectOne("com.phoneinfo.mapper.InfoMapper.searchAllCount");
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
			try {
				reader.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return result;
	}

	@Override
	public List<Info> searchAll(Page p) {
		String path="phoneinfo.xml";
		List<Info> result=new ArrayList<Info>();
		Reader reader=null;
		SqlSession session=null;
		try {
			reader=Resources.getResourceAsReader(path);
			SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
			SqlSessionFactory factory = builder.build(reader);
			session = factory.openSession();
			result = session.selectList("com.phoneinfo.mapper.InfoMapper.searchAll",p);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
			try {
				reader.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return result;
	}

	@Override
	public int update(Info info) {
		String path="phoneinfo.xml";
		int result=0;
		Reader reader=null;
		SqlSession session=null;
		try {
			reader=Resources.getResourceAsReader(path);
			SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
			SqlSessionFactory factory = builder.build(reader);
			session = factory.openSession();
			result = session.update("com.phoneinfo.mapper.InfoMapper.update",info);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
		}finally{
			session.close();
			try {
				reader.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return result;
	}

}
